package org.wsff.tools.api.gateway.core.monitor;

import java.io.Serializable;

import org.apache.commons.lang3.time.StopWatch;
import org.wsff.tools.api.gateway.core.AbstractGatewayContext;

/**
 * 网关监控上下文抽象类
 *
 * @author ryan
 * @version Id: AbstractMonitorGatewayContext.java, v 0.1 2022-02-08 14:12 ryan Exp $$
 */
public abstract class AbstractMonitorGatewayContext<Request extends Serializable, Response extends Serializable> extends AbstractGatewayContext<Request, Response>
                                                   implements MonitorGatewayContext<Request, Response> {

    private static final long   serialVersionUID = -7482711956481834358L;
    /** 耗时器 */
    private transient StopWatch stopWatch;

    /** 响应码 */
    private String              code;
    /** 响应信息 */
    private String              message;

    public AbstractMonitorGatewayContext(String name, Request request) {
        super(name, request);
        stopWatch = new StopWatch();
    }

    /**
     * set proxy response code & message.
     *  @param code code
     * @param message message
     */
    @Override
    public void setResponse(String code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * get reqTime
     *
     * @return reqTime
     */
    @Override
    public long reqTime() {
        return reqTime;
    }

    /**
     * get respTime
     *
     * @return respTime
     */
    @Override
    public long respTime() {
        return reqTime + stopWatch.getTime();
    }

    /**
     * Gets the value of code.
     *
     * @return the value of code
     */
    @Override
    public String code() {
        return code;
    }

    /**
     * Gets the value of message.
     *
     * @return the value of message
     */
    @Override
    public String message() {
        return message;
    }

    /**
     * 开始监控
     */
    @Override
    public void start() {
        if (stopWatch.isStarted() || stopWatch.isStopped()) {
            return;
        }
        stopWatch.start();
    }

    /**
     * 结束监控
     */
    @Override
    public void stop() {
        if (stopWatch.isStopped()) {
            return;
        }
        stopWatch.stop();
    }
}
